<script setup lang="ts">
import { addProduct, deleteProduct, editProduct, getProduct, getProductDetail } from '@/api/marketers/product';
import { reactive, ref, toRefs } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type UploadFile, type UploadFiles } from 'element-plus'; // 根据实际库调整导入路径

import { Plus } from '@element-plus/icons-vue'
import message from '@/utils/message';
import myCookies from '@/utils/myCookies';
import type { UploadProps } from 'element-plus';
import { getCategory, getCategoryDetail } from '@/api/marketers/category';
import { addDateRange, handleTree } from '@/utils/ruoyi';
import { getMerchant } from '@/api/marketers/merchant';
interface Product {
    productId: number;
    name: string;
    price: number;
    stock: number;
    categoryId: number;
    categoryName: string;
    merchantId: number;
    merchantName: string;
    description: string;
    status: number;
    createTime: string;
    img: string;
    imgs: UploadFile[
    ],
    sold:number
    pageNum?:number,
    pageSize?:number,

}
const goodsNameRule = (rule: any, value: any, callback: any) => {

if (!value.trim() ||value.trim() === '') {
    callback(new Error('商品名称不能为空'))
} else if (value.trim().length < 1 || value.trim().length > 20) {
    callback(new Error('长度为1到20位'))
} else {
    callback()
}
}
const imgsRule = (rule: any, value: any, callback: any) => {
if(value === undefined){
  callback(new Error("至少有一张图片"))
}
else if (value[0] == null || value[0] == undefined || value === undefined) {
    callback(new Error("至少有一张图片"))
}else {
    callback()
}
}
const loading  =ref(true)
const searchRef = ref()
const dateRange = ref()
const dialogVisibleImg = ref(false)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const categoryList = ref()
const merchantList = ref()
//获取商品分类列表
getCategory({}).then((response) => {

    (categoryList.value = handleTree(
      response.data.data,
      "categoryId",
      "parentId",
      "children"
    ))

});
//获取商家列表
getMerchant({}).then(response=>{
  merchantList.value=response.data.data
})
//表单标题
const formTitle = ref("")
const total = ref(0);
const tableData = ref<Product[]>([])
const formRef = ref()
const data = reactive({
  form: <Product>{
    stock:0,
    price:0,
    name:'',
    status:1
  },
  queryParams: <Product>{
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    name: [
        { required: true, validator: goodsNameRule, trigger: 'blur' }
    ],
    price: [
        { required: true, message: '必须设置价格' },
        { type: 'number', message: '只能是阿拉伯数字' },
    ],
    stock: [
        { required: true, message: '必须设置库存' },
        { type: 'number', message: '只能是阿拉伯数字' }
    ],
    imgs: [
        { required: true, validator: imgsRule, trigger: 'blur' }
    ],
    categoryId: [
        { required: true, message: '必须设置分类' }
    ],
}
});
const { queryParams, form, rules } = toRefs(data);



//获取商品列表
async function getProductList() {
   loading.value=true
  await getProduct(addDateRange( queryParams.value,dateRange.value)).then((response) => {
        tableData.value = response.data.rows
        total.value = response.data.total
    })
    loading.value=false
}
// 选择分页
const handleSizeChange = (val: number) => {
    queryParams.value.pageSize = val
    getProductList()
}
// 当前页
const handleCurrentChange = (val: number) => {
    queryParams.value.pageNum = val
    getProductList()
}

//默认为新增true
const formAddAndEdit = ref(true)
// 新增商品
const AddForm = () => {
    formTitle.value = "新增商品"
    formAddAndEdit.value = true
    dialogVisible.value = true
}
//修改商品
const handleEdit = async (row: any) => {
    formTitle.value = "修改商品"
    formAddAndEdit.value = false
    dialogVisible.value = true
    await getProductDetail(row.productId).then((response) => {
        form.value = response.data.data
    })
}

// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//提交按钮
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            if (formAddAndEdit.value) {
                await addProduct(form.value).then((response) => {
    ElMessage.success(response.data.msg);
  });
            }
            else {
              await getCategoryDetail(form.value.categoryId).then(response=>{
                 form.value.categoryName=response.data.data.name
                })
                await editProduct(form.value).then((response) => {
    ElMessage.success(response.data.msg);
  });
            }
            dialogVisible.value = false
            getProductList()
        }
    })
}

//查询按钮
const selectSumbit = () => {
  queryParams.value.pageNum = 1;
  getProductList();
};
const selectedRows = ref<Product[]>([]);
const handleSelectionChange = (newSelection: Product[]) => {
  selectedRows.value = newSelection;
  selectedRows.value.length === 0
    ? (iSdeleteUsersButton.value = true)
    : (iSdeleteUsersButton.value = false);
};



const iSdeleteUsersButton = ref(true);

// 单个删除按钮
const handleDelete = async (row: any) => {
    await deleteProduct([row.productId]).then((response) => {
    ElMessage.success(response.data.msg);
  });
    getProductList()
}
// 批量删除按钮
const deleteUsersButton = async () => {
  const ids = selectedRows.value.map((item) => item.productId);


    await ElMessageBox.confirm(
      "确定要删除这些id为 " + ids + " 的商品吗吗？",
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    // 调用删除接口
    await deleteProduct(ids);
    // 更新表格数据（过滤掉已删除项）
    getProductList();
    ElMessage.success("删除成功");

};

//图片上传成功回调
const success = (response: any) => {
    form.value.img = response.data
}










const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisibleImg.value = true
}
const handleRemove = (uploadFile: any, uploadFiles: any[]) => {
    form.value.imgs = uploadFiles
}
// 上传成功时钩子
const handleSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    uploadFile.url = response.data
    console.log(response.data)
}
// 预览图片数组
const imgPerview = (imgList: any) => {
    const imgs: string[] = []
    imgList.forEach((item: any) => { imgs.push(item.url) })
    return imgs
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg'&&  rawFile.type !== 'image/mevc' && rawFile.type !=='image/gif'
        && rawFile.type !=='image/heif'
    ) {
        ElMessage.error('只能上传jpeg/jpg/png')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

getProductList()
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header style="margin: auto; max-width: 95%; height: auto">
        <el-form :inline="true" :model="queryParams" ref="searchRef" label-width="68px">
          <el-form-item prop="productId" label="商品id">
            <el-input
              v-model="queryParams.productId"
              style="width: 240px"
              placeholder="商品id"
            ></el-input>
          </el-form-item>
          <el-form-item prop="name" label="商品名称">
            <el-input
              v-model="queryParams.name"
              style="width: 240px"
              placeholder="商品名称"
            >
              style="width: 240px"</el-input
            ></el-form-item
          >
          <el-form-item prop="stock" label="库存">
            <el-input
              v-model.number="queryParams.stock"
              style="width: 240px"
              placeholder="库存数量"
            ></el-input
          ></el-form-item>
          <el-form-item prop="categoryId" label="分类">
            <el-tree-select
              v-model="queryParams.categoryId"
              :data="categoryList"
              check-strictly
              :props="{ label: 'name', value: 'categoryId' }"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>

          <el-form-item prop="status" label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              style="width: 240px"
            >
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="0"
            /></el-select>
          </el-form-item>
          <el-form-item label="范围时间">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="selectSumbit">查询</el-button>
            <el-button
              type="primary"
              @click="resetForm(searchRef), (dateRange = null), getProductList()"
              plain
              >重置</el-button
            >
            <el-button
              type="danger"
              @click="deleteUsersButton"
              :disabled="iSdeleteUsersButton"
              >批量删除</el-button
            >
          </el-form-item>
        </el-form>
      </el-header>

      <el-main class="" style="margin: auto; width: 95%">
        <el-button @click="AddForm">新增</el-button>
        <el-divider />

        <el-table
          :data="tableData"
          v-loading="loading"
          style="height: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column fixed type="selection" width="55" />
          <el-table-column prop="productId" label="商品ID" width="100" />
          <el-table-column prop="name" label="商品名称" width="180" />
          <el-table-column prop="price" label="价格">
            <template #default="scope">
              <span>￥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存数量" />
          <el-table-column prop="categoryName" label="所属分类" />
          <!-- <el-table-column prop="merchantName" label="商家名称" /> -->
          <el-table-column prop="description" label="商品详情" width="180" />
          <el-table-column prop="sold" label="销量" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :value="scope.row.status">{{
                scope.row.status ? "上架" : "下架"
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="updateTime" label="修改时间" />
          <el-table-column prop="imgs" label="图片" width="180">
            <template #default="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.img"
                :preview-src-list="imgPerview(scope.row.imgs)"
                show-progress
                fit="cover"
                :preview-teleported="true"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="handleEdit(scope.row)">
                修改
              </el-button>
              <el-popconfirm title="确定要删除吗？" @confirm="handleDelete(scope.row)">
                <template #reference>
                  <el-button link type="primary" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="common-footer">
        <el-affix position="bottom" :offset="40">
          <el-pagination
            style="display: flex; justify-content: center; margin-top: 20px"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 15, 25]"
            size="default"
            :background="true"
            layout="sizes, prev, pager, next,jumper,total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-affix>
      </el-footer>
    </el-container>
  </div>
  <!-- 添加修改 -->
  <el-dialog
    v-model="dialogVisible"
    style="max-width: 600px"
    :title="formTitle"
    width="800"
    @close="resetForm(formRef)"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="auto">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="name" label="商品名称">
            <el-input v-model.trim="form.name" placeholder="商品名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="price" label="价格">
            <el-input-number
              v-model="form.price"
              :precision="2"
              :step="1"
              :max="99999999.99"
              :min="0.01"
              :controls="false"
              style="width: 240px"
            >
              <template #suffix> 元 </template>
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="stock" label="库存数量">
            <el-input-number
              v-model="form.stock"
              step-strictly
              :step="1"
              :max="99999"
              :min="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="categoryId" label="分类">
            <el-tree-select
              v-model="form.categoryId"
              :data="categoryList"
              check-strictly
              :props="{ label: 'name', value: 'categoryId' }"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="description" label="商品详情">
            <el-input v-model="form.description" placeholder="商品详情"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="imgs" label="图片">
            <el-upload
              v-model:file-list="form.imgs"
              action="/upload"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisibleImg">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="status" label="状态">
            <el-select
              v-model="form.status"
              placeholder="请选择状态"
              style="width: 240px"
            >
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="0"
            /></el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button @click="submitForm(formRef)">确定</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
